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-nice-subarray/discuss/2527327/Python3-Sliding-Window | class Solution:
def longestNiceSubarray(self, nums: List[int]) -> int:
l = 0
r = 0
n = len(nums)
curr_mask = 0
ans = 1
while r < n:
while l < r and curr_mask & nums[r] != 0:
curr_mask = curr_mask ^ nums[l]
l += 1
curr_mask = curr_mask | nums[r]
r += 1
ans = max(ans, r - l)
return ans | longest-nice-subarray | [Python3] Sliding Window | helnokaly | 3 | 79 | longest nice subarray | 2,401 | 0.48 | Medium | 32,800 |
https://leetcode.com/problems/longest-nice-subarray/discuss/2527365/Python-or-Sliding-window | class Solution:
def longestNiceSubarray(self, nums: List[int]) -> int:
n = len(nums)
left, right = 0, 1
usedBits = nums[0]
longestNice = 1
while right < n:
while right < n and usedBits & nums[right] == 0: # while there is no bit overlap keep making longer to the right
usedBits |= nums[right] # turn on bits from right num
right += 1
longestNice = max(longestNice, right - left)
usedBits ^= nums[left] # turn off bits from left num
left += 1
return longestNice | longest-nice-subarray | Python | Sliding window | sr_vrd | 2 | 88 | longest nice subarray | 2,401 | 0.48 | Medium | 32,801 |
https://leetcode.com/problems/longest-nice-subarray/discuss/2845519/Clean-Fast-Python3 | class Solution:
def longestNiceSubarray(self, nums: List[int]) -> int:
n, nice = len(nums), 1
cur_bits = nums[0]
l, r = 0, 1
while r < n:
nice = max(nice, r - l)
if cur_bits & nums[r]:
cur_bits ^= nums[l]
l += 1
else:
cur_bits |= nums[r]
r += 1
return max(nice, r - l) | longest-nice-subarray | Clean, Fast Python3 | ryangrayson | 0 | 1 | longest nice subarray | 2,401 | 0.48 | Medium | 32,802 |
https://leetcode.com/problems/longest-nice-subarray/discuss/2816441/Python3-Sliding-Window-%2B-Bit-Manipulation-Solution-Explained | class Solution:
def longestNiceSubarray(self, nums: List[int]) -> int:
left = res = mask = 0
for right, num in enumerate(nums):
while (mask & num): #while mask has set bits in same position as in num (stop once mask & num == 0, so we can add num)
mask ^= nums[left] #using xor to remove the bits set by nums[left] (1 ^ 1 = 0)
left += 1
mask |= num #setting the bits in mask that are set in nums
res = max(res, right - left + 1)
return res | longest-nice-subarray | [Python3] Sliding Window + Bit Manipulation Solution Explained | Saksham003 | 0 | 5 | longest nice subarray | 2,401 | 0.48 | Medium | 32,803 |
https://leetcode.com/problems/longest-nice-subarray/discuss/2536775/Python-3-sliding-window-with-backward-validating | class Solution:
def longestNiceSubarray(self, nums: List[int]) -> int:
if not nums: return 0
l = 0
ans = 1
for r in range(1, len(nums)):
# check validation with previous numbers - backwards
i = r-1
while i >= l:
if not nums[r] & nums[i]:
i -= 1
# once the validation doesn't hold at i, start from i+1 for next iteration
else:
l = i + 1
break
ans = max(ans, r-l+1)
return ans | longest-nice-subarray | [Python 3] sliding window with backward validating | oO00Oo | 0 | 16 | longest nice subarray | 2,401 | 0.48 | Medium | 32,804 |
https://leetcode.com/problems/longest-nice-subarray/discuss/2528681/Sliding-Window-or-Well-Explained-or-easy-understanding | class Solution:
def longestNiceSubarray(self, nums: List[int]) -> int:
ans = 0
# temp to store the OR value
temp_or = 0
# pivot for left and right index
left, right = 0, 0
# sliding window
while right < len(nums):
# still NICE! -> update OR value and increase RIGHT
if nums[right] & temp_or == 0:
temp_or |= nums[right]
ans = max(right - left + 1, ans)
right += 1
# NOT nice -> update left pivot, reduce OR value
else:
temp_or -= nums[left]
left += 1
return ans | longest-nice-subarray | 📍Sliding Window | Well Explained | easy understanding | gg21aping | 0 | 38 | longest nice subarray | 2,401 | 0.48 | Medium | 32,805 |
https://leetcode.com/problems/longest-nice-subarray/discuss/2528447/python3-Sliding-window-sol-for-reference | class Solution:
def longestNiceSubarray(self, nums) -> int:
rolling = 0
ans = 0
idx = 0
start = 0
end = len(nums)
while idx < end:
n = nums[idx]
if rolling & n == 0:
rolling += n
else:
ans = max(idx-start, ans)
while start < idx and rolling and (rolling - nums[start]) & n != 0:
rolling -= nums[start]
start += 1
start += 1
rolling = nums[start]
idx = start
idx += 1
return max(ans, idx-start) | longest-nice-subarray | [python3] Sliding window sol for reference | vadhri_venkat | 0 | 13 | longest nice subarray | 2,401 | 0.48 | Medium | 32,806 |
https://leetcode.com/problems/longest-nice-subarray/discuss/2527659/Sliding-Window-Python | class Solution:
def longestNiceSubarray(self, nums: List[int]) -> int:
def isValid(s, e):
for i in range(s, e + 1):
for j in range(s, e + 1):
if i != j and (nums[j] & nums[i]) != 0:
return False
return True
ans = 0
start = 0
for end in range(len(nums)):
while start < end and not isValid(start, end):
start += 1
ans = max(ans, end - start + 1)
return ans | longest-nice-subarray | Sliding Window - Python | EdwinJagger | 0 | 25 | longest nice subarray | 2,401 | 0.48 | Medium | 32,807 |
https://leetcode.com/problems/longest-nice-subarray/discuss/2527520/O(n)-using-sliding-Windows-with-bit-operator-or-and-and | class Solution:
def longestNiceSubarray(self, nums: List[int]) -> int:
n = len(nums)
ans = 0
last = -1
ror = 0
for first in range(n):
if first > last:
last = first
ror = nums[first]
else:
ror = nums[first]
for i in range(first + 1, last + 1):
ror = ror | nums[i]
while last+1<=n-1 and (ror & nums[last+1] == 0):
ror = ror | nums[last+1]
last = last + 1
ans = max(ans, last - first + 1)
# print((first, last), ror, ans)
return ans | longest-nice-subarray | O(n) using sliding Windows with bit operator or and and | dntai | 0 | 20 | longest nice subarray | 2,401 | 0.48 | Medium | 32,808 |
https://leetcode.com/problems/meeting-rooms-iii/discuss/2527343/Python-or-More-heap-extravaganza | class Solution:
def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
meetings.sort() # make sure start times are sorted!!
meetingCount = [0 for _ in range(n)]
availableRooms = list(range(n)); heapify(availableRooms)
occupiedRooms = []
for start, end in meetings:
while occupiedRooms and start >= occupiedRooms[0][0]:
heappush(availableRooms, heappop(occupiedRooms)[1]) # frees room and makes it available
if availableRooms:
roomNumber = heappop(availableRooms) # assigns next available room
else:
freedEnd, roomNumber = heappop(occupiedRooms) # waits until the next room that would be available gets free
end += freedEnd - start
heappush(occupiedRooms, (end,roomNumber)) # make note that the ruom is occupied and when the assigned meeting ends
meetingCount[roomNumber] += 1 # update meeting counter
return sorted([(count, i) for i, count in enumerate(meetingCount)], key = lambda x: (-x[0], x[1]))[0][1] # find room with most meetings | meeting-rooms-iii | Python | More heap extravaganza | sr_vrd | 1 | 41 | meeting rooms iii | 2,402 | 0.332 | Hard | 32,809 |
https://leetcode.com/problems/meeting-rooms-iii/discuss/2594551/Python-or-Heap-solution-with-easy-explanation | class Solution:
def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
currentMeetHeap = []
numOfMeet = n * [0]
currentMeet = n * [False]
meetings.sort()
# Removes ended meetings from the heap.
def clearEnded(cutoff):
while len(currentMeetHeap)>0 and cutoff>=currentMeetHeap[0][0]:
ended = heapq.heappop(currentMeetHeap)
currentMeet[ended[1]] = False
def addMeeting(room, end):
currentMeet[room] = True
numOfMeet[room] += 1
heapq.heappush(currentMeetHeap, [end,room])
def getFirstMax():
maxMeet = 0
maxMeetRoom = 0
for i in range(len(numOfMeet)):
meets = numOfMeet[i]
if meets > maxMeet:
maxMeet = meets
maxMeetRoom = i
return maxMeetRoom
for meeting in meetings:
# First check if theres any empty rooms at the start of the current meeting.
# If so, use this room.
clearEnded(meeting[0])
added = False
for i in range(n):
if not currentMeet[i]:
addMeeting(i, meeting[1])
added = True
break
if (added):
continue
# If no meeting rooms initially available, pull a meeting from the heap.
# We need to adjust the end time to account for the wait.
firstAvailable = heapq.heappop(currentMeetHeap)
addMeeting(firstAvailable[1], meeting[1]+(firstAvailable[0]-meeting[0]))
return getFirstMax() | meeting-rooms-iii | Python | Heap solution with easy explanation | bpower2009 | 0 | 38 | meeting rooms iii | 2,402 | 0.332 | Hard | 32,810 |
https://leetcode.com/problems/meeting-rooms-iii/discuss/2532218/2401.-Longest-Nice-Subarray-Python3 | class Solution:
def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
meetings.sort()
rooms = [0] * n
def indexOfRoom(meeting):
result = None
for i in range(n):
if rooms[i] <= meeting[0]:
rooms[i] = meeting[1]
result = i
break
if result is None:
minVal = min(rooms)
result = rooms.index(minVal)
rooms[result] += meeting[1] - meeting[0]
return result
frequences = [0] * n
for meeting in meetings:
index = indexOfRoom(meeting)
frequences[index] += 1
return frequences.index(max(frequences)) | meeting-rooms-iii | 2401. Longest Nice Subarray - Python3 | KevinWayneDurant | 0 | 15 | meeting rooms iii | 2,402 | 0.332 | Hard | 32,811 |
https://leetcode.com/problems/meeting-rooms-iii/discuss/2530376/Python-3Two-heaps-solution | class Solution:
def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
cnt = [0] * n
available = list(range(n))
heapify(available)
used = []
meetings.sort(reverse=True)
while meetings:
start, end = meetings.pop()
# backfill room into available
while used and used[0][0] <= start:
_, room = heappop(used)
heappush(available, room)
if available:
room = heappop(available)
heappush(used, (end, room))
cnt[room] += 1
# if no available room, means all current used room will end after curret meeting start time
# then pop out the earliest and smallest room number, new end time will be the popped end time + meeting duration
else:
room_end, room = heappop(used)
heappush(used, (room_end+end-start, room))
cnt[room] += 1
return cnt.index(max(cnt)) | meeting-rooms-iii | [Python 3]Two heaps solution | chestnut890123 | 0 | 29 | meeting rooms iii | 2,402 | 0.332 | Hard | 32,812 |
https://leetcode.com/problems/meeting-rooms-iii/discuss/2529948/Python-Solution-With-Dictionary | class Solution:
def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
d = dict()
for i in range(n):
d[i] = 0
meetings = sorted(meetings,key = lambda x:(x[0],x[1]))
room = [i for i in range(n)]
for i in range(len(meetings)):
flag=False
for j in range(n):
if room[j]<=meetings[i][0]:
room[j]=meetings[i][1]
d[j]+=1
flag=True
break
if not flag:
m=min(room)
j=room.index(m)
room[j]=room[j]+(meetings[i][1]-meetings[i][0])
d[j]+=1
c=0
x=0
for k,v in d.items():
if v>c:
x=k
c=v
elif v==c:
x=min(x,k)
return x | meeting-rooms-iii | Python Solution With Dictionary | a_dityamishra | 0 | 23 | meeting rooms iii | 2,402 | 0.332 | Hard | 32,813 |
https://leetcode.com/problems/meeting-rooms-iii/discuss/2529020/python3-heapq-solution-for-reference. | class Solution:
def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
mr = []
m = [0]*n
meetings.sort(key = lambda x: x[0])
available_meeting_rooms = list(zip(range(n), [0]*n))
for s,e in meetings:
while mr and mr[0][0] <= s:
ea, mridx = heapq.heappop(mr)
heapq.heappush(available_meeting_rooms, (mridx, ea))
if len(available_meeting_rooms) == 0:
free_since, mridx = heapq.heappop(mr)
heapq.heappush(mr, (free_since + (e-s), mridx))
m[mridx] += 1
else:
mridx, free_since = heapq.heappop(available_meeting_rooms)
heapq.heappush(mr, (max(free_since, s) + (e-s), mridx))
m[mridx] += 1
return m.index(max(m)) | meeting-rooms-iii | [python3] heapq solution for reference. | vadhri_venkat | 0 | 16 | meeting rooms iii | 2,402 | 0.332 | Hard | 32,814 |
https://leetcode.com/problems/meeting-rooms-iii/discuss/2527552/Python3-min-heap-%2B-index-array | class Solution:
def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
number_of_meetings_in_room = [0] * n
room_is_available = [0] * n
meetings.sort()
heap = []
for meeting_start, meeting_end in meetings:
meeting_length = meeting_end - meeting_start
while heap and heap[0][0] <= meeting_start:
end_time, room_number = heapq.heappop(heap)
# MAKE SURE TO MAKE ROOM AVAILABLE AFTER!!
room_is_available[room_number] = 0
if len(heap) < n:
for room_number, available in enumerate(room_is_available):
if available == 0:
number_of_meetings_in_room[room_number] += 1
room_is_available[room_number] = meeting_start + meeting_length
heapq.heappush(heap, (meeting_start + meeting_length, room_number))
break
else:
end_time, room_number = heapq.heappop(heap)
heapq.heappush(heap, (end_time + meeting_length, room_number))
number_of_meetings_in_room[room_number] += 1
return -max((meetings, -index) for index, meetings in enumerate(number_of_meetings_in_room))[1] | meeting-rooms-iii | [Python3] min heap + index array | _snake_case | 0 | 10 | meeting rooms iii | 2,402 | 0.332 | Hard | 32,815 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2581151/Python-3-oror-2-lines-Counter-oror-TM%3A-9586 | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
ctr = Counter(nums)
return max([c for c in ctr if not c%2], key = lambda x:(ctr[x], -x), default = -1) | most-frequent-even-element | Python 3 || 2 lines, Counter || T/M: 95%/86% | warrenruud | 6 | 268 | most frequent even element | 2,404 | 0.516 | Easy | 32,816 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2839662/Python-or-Easy-Solution | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
seen = {}
for item in nums:
if item % 2 ==0:
seen[item] = 1 if item not in seen else seen[item] + 1
maxx = 0
output = -1
for num, count in seen.items():
if count > maxx:
maxx, output = count, num
elif count == maxx:
output = min(num,output)
return output | most-frequent-even-element | Python | Easy Solution✔ | manayathgeorgejames | 4 | 37 | most frequent even element | 2,404 | 0.516 | Easy | 32,817 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2560284/Python3-2-line | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
freq = Counter(x for x in nums if x&1 == 0)
return min(freq, key=lambda x: (-freq[x], x), default=-1) | most-frequent-even-element | [Python3] 2-line | ye15 | 3 | 173 | most frequent even element | 2,404 | 0.516 | Easy | 32,818 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2795372/Easy-Python-Code-(Beats-100)-oror-Intuitive-Approach-oror-Beginner-Level | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
h={}
for i in nums:
if i%2==0:
if i in h:
h[i]+=1
else:
h[i]=1
o=0
ans=-1
for i in h.keys():
if h[i]>o:
o=h[i]
ans=i
if h[i]==o and i<ans:
ans=i
return ans | most-frequent-even-element | Easy Python Code (Beats 100%) || Intuitive Approach || Beginner Level | Manav_Bhavsar | 1 | 70 | most frequent even element | 2,404 | 0.516 | Easy | 32,819 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2560165/Easy-and-Clear-Solution-Python3 | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
ccc = collections.Counter(nums)
mxe=-1
mx=0
for i in ccc.keys():
if ccc[i]>mx and i%2==0:
mx=ccc[i]
mxe=i
if ccc[i]==mx and i%2==0:
if i<mxe:
mxe=i
return mxe | most-frequent-even-element | Easy & Clear Solution Python3 | moazmar | 1 | 204 | most frequent even element | 2,404 | 0.516 | Easy | 32,820 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2821694/Runtime%3A-712-ms-faster-than-48.62-of-Python3-online-submissions-for-Most-Frequent-Even-Element. | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
l=[]
ans=[]
dic={}
for i in nums:
if i%2==0:
l.append(i)
for i in l:
if i in dic:
dic[i]+=1
else:
dic[i]=1
if len(dic)<=0:
return -1
a=max(dic.values())
for i,j in dic.items():
if j == a:
ans.append(i)
return min(ans) | most-frequent-even-element | Runtime: 712 ms, faster than 48.62% of Python3 online submissions for Most Frequent Even Element. | liontech_123 | 0 | 3 | most frequent even element | 2,404 | 0.516 | Easy | 32,821 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2815027/Python-1-line%3A-Optimal-and-Clean-with-explanation-2-ways%3A-O(n)-time-and-O(n)-space | class Solution:
# 1. use Counter of even elements
# 2. take max of Counter with custom key to tiebreak using smallest, default = -1
# O(nlogn) time : O(n) space
def mostFrequentEven(self, nums: List[int]) -> int:
return max(sorted(Counter([num for num in nums if not num % 2]).items(), key = lambda x : x[0]), key = lambda x : x[1], default = (-1,-1))[0]
# O(n) time : O(n) space
def mostFrequentEven(self, nums: List[int]) -> int:
return max(Counter([x for x in nums if not x % 2]).items(), key = lambda x : (x[1], -x[0]), default = (-1,-1))[0] | most-frequent-even-element | Python 1 line: Optimal and Clean with explanation - 2 ways: O(n) time and O(n) space | topswe | 0 | 6 | most frequent even element | 2,404 | 0.516 | Easy | 32,822 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2767041/understandable-solution | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
l=[]
d={}
res=[]
for i in nums:
if i%2 == 0:
l.append(i)
for i in l:
if i in d:
d[i]+=1
else:
d[i]=1
if d:
s=max(d.values())
else:
return -1
for key,val in d.items():
if val==s:
res.append(key)
return min(res) | most-frequent-even-element | understandable solution | sindhu_300 | 0 | 9 | most frequent even element | 2,404 | 0.516 | Easy | 32,823 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2707529/Python-using-Filter-and-Counter | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
even_nums = list(filter(lambda x:x%2 == 0,nums))
if not even_nums:
return -1
cntr = collections.Counter(even_nums)
even_nums.sort(key=lambda x:(-cntr[x],x))
return even_nums[0] | most-frequent-even-element | Python using Filter and Counter | anandudit | 0 | 10 | most frequent even element | 2,404 | 0.516 | Easy | 32,824 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2699420/Python-solution-clean-code-with-full-comments.-95.66-speed-85.32-space. | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
return check_most_frequent(convert_to_dict(nums))
# Define helper method that will convert integer list into a dictionary.
def convert_to_dict(nums: List[int]):
dic = {}
for i in nums:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
return dic
# This method will search for an even key with the maximum value- most frequent even element.
# While doing so, the method will check if two keys have the same value. If so, then it will take the smallest key from the two.
def check_most_frequent(dic):
# Make variables for the pair (even key, max value).
# If we failed to find a valid key, then the default value is -1.
most_frequent_value = float('-inf')
most_frequent_key = -1
for key in dic.keys():
if key % 2 == 0:
# Search for even key with max value.
if most_frequent_value < dic[key]:
most_frequent_value = dic[key]
most_frequent_key = key
# Take into account different even keys with same values.
elif most_frequent_value == dic[key]:
most_frequent_key = min(most_frequent_key, key)
return most_frequent_key
# Runtime: 292 ms, faster than 95.66% of Python3 online submissions for Most Frequent Even Element.
# Memory Usage: 14.2 MB, less than 85.32% of Python3 online submissions for Most Frequent Even Element.
# If you like my work and found it helpful, then I'll appreciate a like. Thanks! | most-frequent-even-element | Python solution, clean code with full comments. 95.66% speed, 85.32% space. | 375d | 0 | 27 | most frequent even element | 2,404 | 0.516 | Easy | 32,825 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2694071/Python-solution-O(n)-time-complexity | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
hashmap = {}
freq = [[] for i in range(len(nums)+1)]
for num in nums:
if num%2 == 0:
hashmap[num] = hashmap.get(num, 0) + 1
for n, c in hashmap.items():
freq[c].append(n)
if len(hashmap) == 0:
return -1
else:
for i in range(len(freq)-1,0,-1):
if len(freq[i]) != 0:
return min(freq[i]) | most-frequent-even-element | Python solution O(n) time complexity | Furat | 0 | 16 | most frequent even element | 2,404 | 0.516 | Easy | 32,826 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2690786/PYTHON3 | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
d={}
l=[]
for i in nums:
if i%2 == 0:
if i not in d:
d[i]=1
else:
d[i]+=1
if len(d)==0:
return -1
else:
t = max(d.values())
for k,v in d.items():
if v == t:
l.append(k)
return min(l) | most-frequent-even-element | PYTHON3 | Gurugubelli_Anil | 0 | 6 | most frequent even element | 2,404 | 0.516 | Easy | 32,827 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2690785/PYTHON3 | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
d={}
l=[]
for i in nums:
if i%2 == 0:
if i not in d:
d[i]=1
else:
d[i]+=1
if len(d)==0:
return -1
else:
t = max(d.values())
for k,v in d.items():
if v == t:
l.append(k)
return min(l) | most-frequent-even-element | PYTHON3 | Gurugubelli_Anil | 0 | 1 | most frequent even element | 2,404 | 0.516 | Easy | 32,828 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2688070/Bucket-Sort | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
h = {}
res = [[]for i in range(len(nums) + 1)]
for i in nums:
if i % 2 == 0 and i in h:
h[i] += 1
elif i % 2 == 0:
h[i] = 1
else:
continue
#now we only have even elements in the hashmap
for n, c in h.items():
res[c].append(n)
for i in range(len(res)-1,0,-1):
for n in sorted(res[i]):
return n
return -1 | most-frequent-even-element | Bucket Sort | Jazzyb1999 | 0 | 8 | most frequent even element | 2,404 | 0.516 | Easy | 32,829 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2682299/Python3-Solution-oror-O(N)-Time-and-Space-Complexity | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
dic={}
value=-1
count=0
for i in nums:
if i%2==0:
if i not in dic:
dic[i]=0
dic[i]+=1
if dic[i]>count or (dic[i]==count and i<value):
value,count=i,dic[i]
return value | most-frequent-even-element | Python3 Solution || O(N) Time & Space Complexity | akshatkhanna37 | 0 | 11 | most frequent even element | 2,404 | 0.516 | Easy | 32,830 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2672852/Simple-and-Easy-to-Understand-or-Python | class Solution(object):
def mostFrequentEven(self, nums):
hashT = {}
for n in nums:
if n % 2 == 0:
if n not in hashT: hashT[n] = 1
else: hashT[n] += 1
if not(hashT): return -1
freq, ans, i = 0, 0, 0
for n in hashT:
if i == 0: ans, freq = n, hashT[n]
else:
if freq < hashT[n]: freq, ans = hashT[n], n
if ans > n and freq == hashT[n]: ans = n
i += 1
return ans | most-frequent-even-element | Simple and Easy to Understand | Python | its_krish_here | 0 | 30 | most frequent even element | 2,404 | 0.516 | Easy | 32,831 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2626473/Python-defaultdict-single-pass.-O(N)O(N) | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
element = highest_freq= -1
freq = defaultdict(int)
for n in nums:
if n % 2 == 0:
freq[n] += 1
if freq[n] > highest_freq:
highest_freq = freq[n]
element = n
elif freq[n] == highest_freq and n < element:
element = n
return element | most-frequent-even-element | Python, defaultdict, single pass. O(N)/O(N) | blue_sky5 | 0 | 17 | most frequent even element | 2,404 | 0.516 | Easy | 32,832 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2600413/Python-Concise-and-easy-Solution-O(N) | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
# count occurences of even numbers
cn = collections.Counter(num for num in nums if num % 2 == 0)
# iterate over all values and find the smallest one with
# the highest frequency
result = -1
max_amount = 0
for item, amount in cn.items():
if amount > max_amount or (amount == max_amount and item < result):
result = item
max_amount = amount
return result | most-frequent-even-element | [Python] - Concise and easy Solution - O(N) | Lucew | 0 | 58 | most frequent even element | 2,404 | 0.516 | Easy | 32,833 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2600413/Python-Concise-and-easy-Solution-O(N) | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
return min(Counter(x for x in nums if not x % 2).items(), key=lambda x: (-x[1], x[0]), default=[-1])[0] | most-frequent-even-element | [Python] - Concise and easy Solution - O(N) | Lucew | 0 | 58 | most frequent even element | 2,404 | 0.516 | Easy | 32,834 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2573942/Leverage-Counter-with-filter-by-sorting | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
counter = Counter(filter(lambda n: n%2==0, nums))
sorted_ranking = sorted(
counter.items(),
key=lambda t: (t[1], -t[0]), # Sorting descendingly
reverse=True)
return sorted_ranking[0][0] if sorted_ranking else -1 | most-frequent-even-element | Leverage Counter with filter by sorting | puremonkey2001 | 0 | 8 | most frequent even element | 2,404 | 0.516 | Easy | 32,835 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2568392/Python-runtime-O(n)-memory-O(n) | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
d = {}
for e in nums:
if e not in d:
d[e] = 1
else:
d[e] += 1
count = 0
ans = -1
for e in d.keys():
if e % 2 == 0:
if count < d[e]:
count = d[e]
ans = e
if count == d[e] and e < ans:
ans = e
return ans | most-frequent-even-element | Python, runtime O(n), memory O(n) | tsai00150 | 0 | 31 | most frequent even element | 2,404 | 0.516 | Easy | 32,836 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2562920/Counter-and-heap-60-speed | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
h = []
for k, v in Counter(nums).items():
if not k % 2:
heappush(h, (-v, k))
if h:
return heappop(h)[1]
return -1 | most-frequent-even-element | Counter and heap, 60% speed | EvgenySH | 0 | 15 | most frequent even element | 2,404 | 0.516 | Easy | 32,837 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2560644/Python-Solution-With-Dictionary | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
d=dict()
for i in range(len(nums)):
if nums[i]%2==0:
if nums[i] not in d:
d[nums[i]]=1
else:
d[nums[i]]+=1
c=0
ans=0
if d:
for k,v in d.items():
if v>c:
c=v
ans=k
elif v==c:
ans=min(ans,k)
return ans
return -1 | most-frequent-even-element | Python Solution With Dictionary | a_dityamishra | 0 | 41 | most frequent even element | 2,404 | 0.516 | Easy | 32,838 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2560580/Python3-or-Hash-Map-or-Very-Easy-Approach | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
hmap = {}
for num in nums:
if not num & 1: # Check for Even or Odd
hmap[num] = hmap.get(num, 0)+1
if not hmap:
return -1
ans = (1 << 31) # Store Maximum Value
t = 1
for key, val in hmap.items():
if val > t or (val == t and key < ans):
ans = key
t = val
return ans | most-frequent-even-element | Python3 | Hash Map | Very Easy Approach ✔ | leet_satyam | 0 | 30 | most frequent even element | 2,404 | 0.516 | Easy | 32,839 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2560549/Python3-Hash-Map-O(n)-time-and-space | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
freqs = dict()
for n in nums:
if n % 2 == 0 and n not in freqs:
freqs[n] = 1
elif n % 2 == 0 and n in freqs:
freqs[n] += 1
curr_max_freq = float("-inf")
curr_min_num = float("inf")
for k, v in freqs.items():
if v == max(list(freqs.values())):
curr_min_num = min(curr_min_num, k)
return curr_min_num if curr_min_num != float("inf") else -1 | most-frequent-even-element | [Python3] Hash Map - O(n) time & space | hanelios | 0 | 15 | most frequent even element | 2,404 | 0.516 | Easy | 32,840 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2560481/Easy-understanding-Python-solution | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
numberMap = defaultdict(int)
for i in nums:
if i % 2 == 0:
numberMap[i] += 1
if numberMap:
minVal = max(numberMap.values())
res = [x for x in numberMap if numberMap[x] == minVal]
return -1 if not numberMap else min(res) | most-frequent-even-element | Easy understanding Python solution | 113377code | 0 | 33 | most frequent even element | 2,404 | 0.516 | Easy | 32,841 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2560251/Python-hashmap | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
dic = collections.defaultdict(int)
res = -1
amount = 0
even = set()
for n in nums:
if n % 2 == 0:
dic[n] += 1
even.add(n)
for n in even:
if dic[n] > amount:
res = n
amount = dic[n]
elif dic[n] == amount:
res = min(res, n)
else:
continue
return res | most-frequent-even-element | Python hashmap | scr112 | 0 | 59 | most frequent even element | 2,404 | 0.516 | Easy | 32,842 |
https://leetcode.com/problems/most-frequent-even-element/discuss/2560235/Easiest-Single-Pass-Python3-No-hashmap-counters-collections | class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
freq = -1
ans = -1
for i in sorted(set(nums)):
if i%2 == 0 and nums.count(i) > freq:
freq = nums.count(i)
ans = i
return ans | most-frequent-even-element | Easiest Single Pass Python3 - No hashmap, counters, collections | suyashmedhavi | 0 | 48 | most frequent even element | 2,404 | 0.516 | Easy | 32,843 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2560044/Python3-Greedy | class Solution:
def partitionString(self, s: str) -> int:
cur = set()
res = 1
for c in s:
if c in cur:
cur = set()
res += 1
cur.add(c)
return res | optimal-partition-of-string | [Python3] Greedy | 0xRoxas | 9 | 547 | optimal partition of string | 2,405 | 0.744 | Medium | 32,844 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2565920/One-pass-set()-for-substring-100-speed | class Solution:
def partitionString(self, s: str) -> int:
sub_set, ans = set(), 1
for c in s:
if c in sub_set:
ans += 1
sub_set = {c}
else:
sub_set.add(c)
return ans | optimal-partition-of-string | One pass, set() for substring, 100% speed | EvgenySH | 2 | 57 | optimal partition of string | 2,405 | 0.744 | Medium | 32,845 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2829926/Python-O(n)-Time-and-O(n)-Space | class Solution:
def partitionString(self, s: str) -> int:
dict1={}
res=1
for i,c in enumerate(s):
if dict1.get(c,None) is None:
dict1[c]=c
else:
dict1={c:c}
res+=1
return res | optimal-partition-of-string | Python O(n) Time & O(n) Space | smadhuna1234 | 0 | 1 | optimal partition of string | 2,405 | 0.744 | Medium | 32,846 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2821422/Python-easy-to-read-and-understand-or-set | class Solution:
def partitionString(self, s: str) -> int:
i, n, cnt = 0, len(s), 1
seen = set()
while i < n:
#print(seen)
if s[i] in seen:
cnt += 1
seen = set()
seen.add(s[i])
i += 1
return cnt | optimal-partition-of-string | Python easy to read and understand | set | sanial2001 | 0 | 2 | optimal partition of string | 2,405 | 0.744 | Medium | 32,847 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2804516/Python-or-HashMap-or-Set | class Solution:
def partitionString(self, s: str) -> int:
count=0
x=set()
for i in s:
if i in x:
count+=1
x=set([i])
else:
x.add(i)
return count+1 | optimal-partition-of-string | Python | HashMap | Set | Chetan_007 | 0 | 2 | optimal partition of string | 2,405 | 0.744 | Medium | 32,848 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2790163/Set-or-Dictionary-oror-Python3 | class Solution:
def partitionString(self, s: str) -> int:
counter = defaultdict(int)
count = 1
for ch in s:
if counter[ch]:
counter = defaultdict(int)
count += 1
counter[ch] = 1
return count | optimal-partition-of-string | Set or Dictionary || Python3 | joshua_mur | 0 | 2 | optimal partition of string | 2,405 | 0.744 | Medium | 32,849 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2790163/Set-or-Dictionary-oror-Python3 | class Solution:
def partitionString(self, s: str) -> int:
cur = set()
res = 1
for c in s:
if c in cur:
cur = set()
res += 1
cur.add(c)
return res | optimal-partition-of-string | Set or Dictionary || Python3 | joshua_mur | 0 | 2 | optimal partition of string | 2,405 | 0.744 | Medium | 32,850 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2751690/Easy-to-Understand-or-Hashmap-or-Python | class Solution(object):
def partitionString(self, s):
hashT = {}
count = 0
for i, ch in enumerate(s):
if i == 0:
hashT[count] = [ch]
else:
if ch not in hashT[count]:
hashT[count].append(ch)
else:
count += 1
hashT[count] = [ch]
return len(hashT) | optimal-partition-of-string | Easy to Understand | Hashmap | Python | its_krish_here | 0 | 4 | optimal partition of string | 2,405 | 0.744 | Medium | 32,851 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2747118/Python3-Solution-with-using-greedy | class Solution:
def partitionString(self, s: str) -> int:
cnt = 0
idx = 0
while idx < len(s):
seen = set()
while idx < len(s) and s[idx] not in seen:
seen.add(s[idx])
idx += 1
cnt += 1
return cnt | optimal-partition-of-string | [Python3] Solution with using greedy | maosipov11 | 0 | 1 | optimal partition of string | 2,405 | 0.744 | Medium | 32,852 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2701156/Easy-python-solution | class Solution:
def partitionString(self, s: str) -> int:
m=set()
c=1
for i in s:
if i not in m:
m.add(i)
else:
m=set()
m.add(i)
c+=1
return c | optimal-partition-of-string | Easy python solution | Nischay_2003 | 0 | 3 | optimal partition of string | 2,405 | 0.744 | Medium | 32,853 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2694510/Easy-Pythonic-Solution | class Solution:
def partitionString(self, s: str) -> int:
n, count = len(s), 0
res = []
for i in s:
if i in res:
count += 1
res.clear()
res.append(i)
return count+1 | optimal-partition-of-string | Easy Pythonic Solution | RajatGanguly | 0 | 5 | optimal partition of string | 2,405 | 0.744 | Medium | 32,854 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2690807/PYTHON3-BEST | class Solution:
def partitionString(self, s: str) -> int:
count = 0
l = set()
for e in s:
if e in l:
count += 1
l = set(e)
else:
l.add(e)
return count+1 | optimal-partition-of-string | PYTHON3 BEST | Gurugubelli_Anil | 0 | 2 | optimal partition of string | 2,405 | 0.744 | Medium | 32,855 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2642985/Short-Python3 | class Solution:
def partitionString(self, s: str) -> int:
st = set()
ans = 1
for a in s:
if a in st:
st = set()
ans += 1
st.add(a)
return ans | optimal-partition-of-string | Short Python3 | tglukhikh | 0 | 4 | optimal partition of string | 2,405 | 0.744 | Medium | 32,856 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2582276/Easy-Python-Solution-with-Set() | class Solution:
def partitionString(self, s: str) -> int:
res = 1
unic = set()
for ch in s:
if ch not in unic:
unic.add(ch)
else:
res += 1
unic.clear()
unic.add(ch)
return res | optimal-partition-of-string | Easy Python Solution with Set() | GarborSergey | 0 | 23 | optimal partition of string | 2,405 | 0.744 | Medium | 32,857 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2572161/Python3-Simple-Solution-oror-Dictionary | class Solution:
def partitionString(self, s: str) -> int:
d = {}
count = 0
for i in s:
if i in d:
count += 1
d = {i:1}
else:
d[i] = 1
return count+1 | optimal-partition-of-string | [Python3] Simple Solution || Dictionary | abhijeetmallick29 | 0 | 15 | optimal partition of string | 2,405 | 0.744 | Medium | 32,858 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2569211/Clean-Python3-Solution-and-faster-than-93 | class Solution:
def partitionString(self, s: str) -> int:
myHash = {}
ans = 0
for c in s:
if c in myHash:
ans +=1
myHash.clear()
myHash[c]=1
return ans + 1 | optimal-partition-of-string | Clean Python3 Solution and faster than 93% | lixinebo | 0 | 13 | optimal partition of string | 2,405 | 0.744 | Medium | 32,859 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2568403/Python-runtime-O(n)-memory-O(n) | class Solution:
def partitionString(self, s: str) -> int:
count = 0
l = set()
for e in s:
if e in l:
count += 1
l = set(e)
else:
l.add(e)
return count+1 | optimal-partition-of-string | Python, runtime O(n), memory O(n) | tsai00150 | 0 | 19 | optimal partition of string | 2,405 | 0.744 | Medium | 32,860 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2563627/Python-simple-solution | class Solution:
def partitionString(self, s: str) -> int:
ans = 0
while s:
i = 1
while len(set(s[:i])) == len(s[:i]) and i < len(s):
i += 1
if i == len(s):
return ans + (len(set(s)) != len(s)) + 1
ans, s = ans + 1, s[i - 1:]
return ans | optimal-partition-of-string | Python simple solution | Mark_computer | 0 | 14 | optimal partition of string | 2,405 | 0.744 | Medium | 32,861 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2562556/Python-Simple-Solution-O(n)-Easy-to-understand | class Solution:
def partitionString(self, s: str) -> int:
st = set()
res = 1
for c in s:
if c not in st:
st.add(c)
else:
st = set(c)
res += 1
return res | optimal-partition-of-string | Python Simple Solution, O(n), Easy to understand | hahashabi | 0 | 18 | optimal partition of string | 2,405 | 0.744 | Medium | 32,862 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2562219/Very-easy-Python-Solution | class Solution:
def partitionString(self, s: str) -> int:
d = {}
c = 0
for i in s:
if i not in d:
d[i] = 1
else:
d = {}
d[i] = 1
c+=1
return c+1 | optimal-partition-of-string | Very easy Python Solution | Flakes342 | 0 | 9 | optimal partition of string | 2,405 | 0.744 | Medium | 32,863 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2561597/Python-Bitmasking-Simple-to-Understand | class Solution:
def partitionString(self, s: str) -> int:
had = 0
res = 0
for i, c in enumerate(s):
pos = ord(c)-ord('a')
if (1 << pos) & had:
had = 0
res += 1
had |= (1 << pos)
return res+1 | optimal-partition-of-string | Python Bitmasking Simple to Understand | rjnkokre | 0 | 4 | optimal partition of string | 2,405 | 0.744 | Medium | 32,864 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2561438/O(n)-using-hash-map-and-heuristic | class Solution:
def partitionString(self, s: str) -> int:
ans = 0
h = set([])
for i, si in enumerate(s):
if si in h:
ans = ans + 1
h = set([si])
else:
h.add(si)
# print((i,si),h,ans)
if len(h)>0:
ans = ans + 1
return ans | optimal-partition-of-string | O(n) using hash-map and heuristic | dntai | 0 | 1 | optimal partition of string | 2,405 | 0.744 | Medium | 32,865 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2560650/Python-Solution-with-Set | class Solution:
def partitionString(self, s: str) -> int:
se=set()
c=0
for i in s:
if i not in se:
se.add(i)
else:
c+=1
se=set()
se.add(i)
return c+1 | optimal-partition-of-string | Python Solution with Set | a_dityamishra | 0 | 15 | optimal partition of string | 2,405 | 0.744 | Medium | 32,866 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2560638/Python3-or-Beginner-Friendly-or-Sliding-Window | class Solution:
def partitionString(self, s: str) -> int:
ans = ""
res = []
for c in s:
if c in ans:
res.append(ans)
ans = ""
ans += c
else:
ans += c
return len(res)+1 | optimal-partition-of-string | Python3 | Beginner Friendly | Sliding Window ✔ | leet_satyam | 0 | 12 | optimal partition of string | 2,405 | 0.744 | Medium | 32,867 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2560441/python3-sliding-window-sol-for-reference. | class Solution:
def partitionString(self, s: str) -> int:
h = defaultdict(int)
idx = 0
end = len(s)
ans = 0
while idx < end:
c = s[idx]
if h[c] > 0:
h.clear()
ans += 1
h[c] += 1
idx += 1
return ans + 1 | optimal-partition-of-string | [python3] sliding window sol for reference. | vadhri_venkat | 0 | 5 | optimal partition of string | 2,405 | 0.744 | Medium | 32,868 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2560410/Python3-O(n)-sliding-window | class Solution:
def partitionString(self, s: str) -> int:
visited = set()
res = 1
for char in s:
if char not in visited:
visited.add(char)
else:
res += 1
visited = set()
visited.add(char)
return res | optimal-partition-of-string | Python3 O(n) sliding window | xxHRxx | 0 | 6 | optimal partition of string | 2,405 | 0.744 | Medium | 32,869 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2560317/O(n)-Easy-Python-using-Set | class Solution:
def partitionString(self, s: str) -> int:
ans = 1
seen = set()
for i in s:
if i in seen:
seen.clear()
ans += 1
seen.add(i)
return ans | optimal-partition-of-string | O(n) Easy Python using Set | suyashmedhavi | 0 | 16 | optimal partition of string | 2,405 | 0.744 | Medium | 32,870 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2560288/Python3-hash-set | class Solution:
def partitionString(self, s: str) -> int:
seen = set()
ans = 1
for ch in s:
if ch in seen:
ans += 1
seen.clear()
seen.add(ch)
return ans | optimal-partition-of-string | [Python3] hash set | ye15 | 0 | 7 | optimal partition of string | 2,405 | 0.744 | Medium | 32,871 |
https://leetcode.com/problems/optimal-partition-of-string/discuss/2560124/Easy-and-Clear-Solution-python3 | class Solution:
def partitionString(self, s: str) -> int:
count=1
word=""
for i in s:
if i in word:
count+=1
word=i
else:
word+=i
return count | optimal-partition-of-string | Easy & Clear Solution python3 | moazmar | 0 | 9 | optimal partition of string | 2,405 | 0.744 | Medium | 32,872 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2560020/Min-Heap | class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
pq = []
for left, right in sorted(intervals):
if pq and pq[0] < left:
heappop(pq)
heappush(pq, right)
return len(pq) | divide-intervals-into-minimum-number-of-groups | Min Heap | votrubac | 227 | 5,600 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,873 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2560042/Python3-Sort-%2B-Heap | class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
intervals.sort()
pq = []
for interval in intervals:
if not pq or interval[0] <= pq[0]:
heapq.heappush(pq, interval[1])
else:
heapq.heappop(pq)
heapq.heappush(pq, interval[1])
return len(pq) | divide-intervals-into-minimum-number-of-groups | [Python3] Sort + Heap | helnokaly | 3 | 121 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,874 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2560007/Python3Rust-Max-DP-Overlap | class Solution:
def minGroups(self, I: List[List[int]]) -> int:
max_val = max([v for _, v in I])
dp = [0]*(max_val + 2)
#Define intervals
for u, v in I:
dp[u] += 1
dp[v + 1] -= 1
#Compute prefix sum to get frequency
for idx in range(1, len(dp)):
dp[idx] += dp[idx - 1]
#Return maximum overlap
return max(dp) | divide-intervals-into-minimum-number-of-groups | [Python3/Rust] Max DP Overlap | 0xRoxas | 3 | 236 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,875 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2598484/Python3-Solution-or-O(nlogn) | class Solution:
def minGroups(self, A):
A = list(map(sorted, zip(*A)))
ans, j = 1, 0
for i in range(1, len(A[0])):
if A[0][i] > A[1][j]: j += 1
else: ans += 1
return ans | divide-intervals-into-minimum-number-of-groups | ✔ Python3 Solution | O(nlogn) | satyam2001 | 1 | 36 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,876 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2690860/PYTHON3 | class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
A = []
for a,b in intervals:
A.append([a, 1])
A.append([b + 1, -1])
y = x = 0
for a, diff in sorted(A):
x += diff
y = max(y,x)
return y | divide-intervals-into-minimum-number-of-groups | PYTHON3 | Gurugubelli_Anil | 0 | 6 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,877 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2668860/Python3-or-Sweep-Line | class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
freq=defaultdict(int)
for a,b in intervals:
freq[a]+=1
freq[b+1]-=1
ans=0
currSum=0
for f in sorted(freq.keys()):
currSum+=freq[f]
ans=max(ans,currSum)
return ans | divide-intervals-into-minimum-number-of-groups | [Python3] | Sweep Line | swapnilsingh421 | 0 | 11 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,878 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2567256/Accumulate-boundaries-85-speed | class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
boundaries = defaultdict(int)
for left, right in intervals:
boundaries[left] += 1
boundaries[right + 1] -= 1
return max(accumulate([boundaries[k] for k in
sorted(boundaries.keys())])) | divide-intervals-into-minimum-number-of-groups | Accumulate boundaries, 85% speed | EvgenySH | 0 | 14 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,879 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2560988/Python3-or-Heap-or-Beginner-Friendly | class Solution:
def minGroups(self, inter: List[List[int]]) -> int:
inter.sort()
heap = []
heapify(heap)
for i, j in inter:
if heap and heap[0] < i:
heappop(heap)
heappush(heap, j)
return len(heap) | divide-intervals-into-minimum-number-of-groups | Python3 | Heap | Beginner Friendly ✔ | leet_satyam | 0 | 48 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,880 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2560668/python3-heapq-sol-for-reference | class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
intervals.sort()
st = [intervals[0][1]]
for s,e in intervals[1:]:
end = heapq.heappop(st)
if end < s:
heapq.heappush(st, e)
else:
heapq.heappush(st, e)
heapq.heappush(st, end)
return len(st) | divide-intervals-into-minimum-number-of-groups | [python3] heapq sol for reference | vadhri_venkat | 0 | 17 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,881 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2560448/Python3-min-heap-Solution | class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
intervals.sort(key = lambda x : x[0])
groups = [intervals[0][1]]
res = 1
heapify(groups)
for start, end in intervals[1:]:
end_time = groups[0]
if start > end_time:
heappop(groups)
heappush(groups, end)
res = max(res, len(groups))
return res | divide-intervals-into-minimum-number-of-groups | Python3 min heap Solution | xxHRxx | 0 | 11 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,882 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2560333/Min-Heap-or-Python | class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
intervals.sort()
heap = []
number = 1
for interval in intervals:
if heap == []:
heapq.heappush(heap, interval[1])
else:
minvalue = heapq.heappop(heap)
if interval[0] > minvalue:
heapq.heappush(heap, interval[1])
else:
heapq.heappush(heap, minvalue)
heapq.heappush(heap, interval[1])
number += 1
return number
``` | divide-intervals-into-minimum-number-of-groups | Min Heap | Python | mdai26 | 0 | 24 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,883 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2560325/Python3-Simple-solution-oror-O(n) | class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
arr = []
for i in intervals:
arr.append([i[0], 0])
arr.append([i[1], 1])
arr.sort()
# print(arr)
ans = 0
x = 0
for i in arr:
if i[1]:
x -= 1
else:
x += 1
ans = max(ans, x)
return ans | divide-intervals-into-minimum-number-of-groups | [Python3] Simple solution || O(n) | anhiks | 0 | 38 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,884 |
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2560292/Python3-line-sweep | class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
line = []
for x, y in intervals:
line.append((x, 1))
line.append((y+1, 0))
ans = prefix = 0
for x, k in sorted(line):
if k: prefix += 1
else: prefix -= 1
ans = max(ans, prefix)
return ans | divide-intervals-into-minimum-number-of-groups | [Python3] line sweep | ye15 | 0 | 23 | divide intervals into minimum number of groups | 2,406 | 0.454 | Medium | 32,885 |
https://leetcode.com/problems/longest-increasing-subsequence-ii/discuss/2591153/Python-runtime-O(n-logn)-memory-O(n) | class Solution:
def getmax(self, st, start, end):
maxi = 0
while start < end:
if start%2:#odd
maxi = max(maxi, st[start])
start += 1
if end%2:#odd
end -= 1
maxi = max(maxi, st[end])
start //= 2
end //= 2
return maxi
def update(self, st, maxi, n):
st[n] = maxi
while n > 1:
n //= 2
st[n] = max(st[2*n], st[2*n+1])
def lengthOfLIS(self, nums: List[int], k: int) -> int:
ans = 1
length = max(nums)
st = [0]*length*2
for n in nums:
n -= 1
maxi = self.getmax(st, max(0, n-k)+length, n+length) + 1
self.update(st, maxi, n+length)
ans = max(maxi, ans)
return ans | longest-increasing-subsequence-ii | Python, runtime O(n logn), memory O(n) | tsai00150 | 0 | 114 | longest increasing subsequence ii | 2,407 | 0.209 | Hard | 32,886 |
https://leetcode.com/problems/longest-increasing-subsequence-ii/discuss/2561362/O(nlogn)-using-dynamic-programming-with-segment-tree-(illustration-examples) | class Solution:
def lengthOfLIS(self, nums: List[int], k: int) -> int:
"""
"""
##############
# Range Minimum Query using Segment Tree
##############
def init(tree, value, k, left, right):
if len(tree)<k+1:
tree.extend([None] * (k+1-len(tree)))
if right - left == 1:
tree[k] = value
return
mid = (left + right)//2
init(tree, value, 2*k, left, mid)
init(tree, value, 2*k+1, mid, right)
tree[k] = max(tree[2*k], tree[2*k+1])
def update(tree, value, pos, k, left, right):
if right - left == 1: # only 1 elements
tree[k] = value
return
mid = (left + right)//2
if pos<mid:
update(tree, value, pos, 2*k, left, mid)
else:
update(tree, value, pos, 2*k+1, mid, right)
tree[k] = max(tree[2*k], tree[2*k+1])
def query(tree, l, r, k, left, right):
if l>=r:
return None
elif l<=left and right<=r:
return tree[k]
mid = (left + right)//2
v1 = query(tree, l, min(mid, r), 2*k, left, mid)
v2 = query(tree, max(l, mid), r, 2*k+1, mid, right)
v = [v for v in [v1, v2] if v is not None]
ret = None if len(v) == 0 else max(v)
return ret
##############
n = len(nums)
# print(nums, k)
# print(len(nums), max(nums), k)
segt = []
sizet = max(nums) + 1
# init(segt, float("-inf"), 1, 0, sizet)
segt = [float("-inf")] * (4 * sizet)
dp = [1] * n
update(segt, dp[0], nums[0], 1, 0, sizet)
for i in range(1, n):
dpj = query(segt, nums[i]-k, nums[i], 1, 0, sizet)
if dpj is None:
dp[i] = 1
else:
dp[i] = max(dpj + 1, 1)
update(segt, dp[i], nums[i], 1, 0, sizet)
pass
ans = max(dp)
# print("ans:", ans)
# print("=" * 20)
return ans
# print = lambda *a, **aa: () | longest-increasing-subsequence-ii | O(nlogn) using dynamic programming with segment tree (illustration examples) | dntai | 0 | 97 | longest increasing subsequence ii | 2,407 | 0.209 | Hard | 32,887 |
https://leetcode.com/problems/count-days-spent-together/discuss/2601983/Very-Easy-Question-or-Visual-Explanation-or-100 | class Solution:
def countDaysTogether(self, arAl: str, lAl: str, arBo: str, lBo: str) -> int:
months = [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
start = max(arAl, arBo)
end = min(lAl, lBo)
startDay = int(start[3:])
startMonth = int(start[:2])
endDay = int(end[3:])
endMonth = int(end[:2])
if start > end:
return 0
if startMonth == endMonth:
return endDay-startDay+1
elif startMonth < endMonth:
return months[startMonth]-startDay + endDay + 1 + sum(months[m] for m in range(startMonth+1, endMonth)) | count-days-spent-together | Very Easy Question | Visual Explanation | 100% | leet_satyam | 3 | 78 | count days spent together | 2,409 | 0.428 | Easy | 32,888 |
https://leetcode.com/problems/count-days-spent-together/discuss/2592748/Python-Simple-To-Understand-Solution | class Solution:
def calculate(self, time):
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return sum(days[:int(time.split('-')[0]) - 1]) + int(time.split('-')[1])
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
alice = [self.calculate(arriveAlice), self.calculate(leaveAlice)]
bob = [self.calculate(arriveBob), self.calculate(leaveBob)]
if bob[0] <= alice[0] <= bob[1]:
if bob[1] <= alice[1]:
return bob[1] - alice[0] + 1
else:
return alice[1] - alice[0] + 1
elif alice[0] <= bob[0] <= alice[1]:
if alice[1] <= bob[1]:
return alice[1] - bob[0] + 1
else:
return bob[1] - bob[0] + 1
else:
return 0 | count-days-spent-together | Python Simple To Understand Solution | cyber_kazakh | 1 | 34 | count days spent together | 2,409 | 0.428 | Easy | 32,889 |
https://leetcode.com/problems/count-days-spent-together/discuss/2843939/Find-days-difference-between-max-arrive-time-and-min-leave-time-Python3 | class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
self.month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# print(self.get_days('09-01', '10-19'))
if arriveBob>leaveAlice or arriveAlice> leaveBob:
return 0
# arrive = max(arriveAlice, arriveBob)
# leave = min(leaveAlice, leaveBob)
# print('arrive is', arrive)
# print('leave is', leave)
return self.get_days(max(arriveAlice, arriveBob), min(leaveAlice, leaveBob))
def get_days(self, start, end):
s_m, s_d = start.split('-')
e_m, e_d = end.split('-')
if s_m==e_m:
return int(e_d)-int(s_d)+1
else:
days = 0
for i in range(int(s_m), int(e_m)):
days += self.month_days[i-1]
days-=int(s_d)-1
days+=int(e_d)
return days | count-days-spent-together | Find days difference between max arrive time and min leave time [Python3] | ben_wei | 0 | 1 | count days spent together | 2,409 | 0.428 | Easy | 32,890 |
https://leetcode.com/problems/count-days-spent-together/discuss/2779602/Python3-solution | class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
monthDatesMap = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30,
7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
# need a helper function to compare two dates
def datesComparison(date1, date2):
# check if date1 >= date2
month1 = int(date1[0:2])
month2 = int(date2[0:2])
if month1 > month2:
return(True)
elif month1 == month2:
if int(date1[3:]) >= int(date2[3:]):
return(True)
return(False)
def datesDifference(date1, date2):
# make sure date2 is >= date1
month1 = int(date1[0:2])
month2 = int(date2[0:2])
dateDiff = 0
if month2 == month1:
dateDiff = int(date2[3:]) - int(date1[3:]) + 1
else:
for tempMonth in range(month1, month2):
if tempMonth == month1:
dateDiff += (monthDatesMap[tempMonth] - int(date1[3:]) + 1)
else:
dateDiff += monthDatesMap[tempMonth]
dateDiff += int(date2[3:])
return(dateDiff)
# figure out who arrives earlier
if datesComparison(arriveAlice, arriveBob):
# Bob arrives earlier
earlierPersonArrival = arriveBob
earlierPersonLeave = leaveBob
laterPersonArrival = arriveAlice
laterPersonLeave = leaveAlice
else:
# Alice arrives earlier
earlierPersonArrival = arriveAlice
earlierPersonLeave = leaveAlice
laterPersonArrival = arriveBob
laterPersonLeave = leaveBob
if not datesComparison(earlierPersonLeave, laterPersonArrival):
# if earlier person leaves stricly before later personal arrival
return(0)
else:
# if earlier person leaves later than later person arrival
if datesComparison(earlierPersonLeave, laterPersonLeave):
# earlier person leaves later
print((laterPersonLeave, earlierPersonLeave))
return(datesDifference(laterPersonArrival, laterPersonLeave))
else:
# earlier person also leaves earilier
return(datesDifference(laterPersonArrival, earlierPersonLeave)) | count-days-spent-together | Python3 solution | user7867e | 0 | 5 | count days spent together | 2,409 | 0.428 | Easy | 32,891 |
https://leetcode.com/problems/count-days-spent-together/discuss/2774964/Easy-and-clean-code | class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def convert(date):
a,b = map(int,date.split("-"))
return sum(month[0:a-1])+b
arriveAlice = convert(arriveAlice)
leaveAlice = convert(leaveAlice)
arriveBob = convert(arriveBob)
leaveBob = convert(leaveBob)
left = max(arriveAlice, arriveBob)
right = min(leaveAlice,leaveBob)
return max(0,right-left+1) | count-days-spent-together | Easy and clean code | rkgupta1298 | 0 | 4 | count days spent together | 2,409 | 0.428 | Easy | 32,892 |
https://leetcode.com/problems/count-days-spent-together/discuss/2770720/Python3-simple-solution | class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
a = list(map(int, arriveAlice.split("-"))) #Alice arrival
b = list(map(int, arriveBob.split("-"))) #Alice departure
c = list(map(int, leaveAlice.split("-"))) #Bob arrival
d = list(map(int, leaveBob.split("-"))) #Bob departure
months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
count = 0
# which date is bigger arrival of alice or arrival of bob
if (a[0] > b[0] or (a[0] == b[0] and a[1] > b[1])):
x = a
else:
x = b
# which date is smaller departure of alice or departure of bob
if (c[0] < d[0] or (c[0] == d[0] and c[1] < d[1])):
y = c
else:
y = d
# Than we will iterate from x to y and check if the given date is between the arrival of alice and departure of alice and arrival of bob and departure of bob, if the date is between we will increment the count variable and the date will also be increment for nextround
while (x[0] < y[0]) or (x[0] == y[0] and x[1] <= y[1]):
if ((a[0] < x[0] < c[0]) or ((a[0] == x[0] and a[0] != c[0] and a[1] <= x[1]) or (x[0] == c[0] and x[1] <= c[1])) or ((a[0] == x[0] and a[0] == c[0] and a[1] <= x[1] <= c[1]))) and ((b[0] < x[0] < d[0]) or ((b[0] == x[0] and b[0] != d[0] and b[1] <= x[1]) or (x[0] == d[0] and x[1] <= d[1])) or ((b[0] == x[0] and b[0] == d[0] and b[1] <= x[1] <= d[1]))):
count += 1
#increment the current checking date
if x[1] < months[x[0]]:
x[1] += 1
else:
x[0] += 1
x[1] = 1
return count | count-days-spent-together | Python3 simple solution | EklavyaJoshi | 0 | 6 | count days spent together | 2,409 | 0.428 | Easy | 32,893 |
https://leetcode.com/problems/count-days-spent-together/discuss/2768504/Python-Beginner-Friendly-Explained | class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
daysPerMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def monthDaytoDays(monthDate):
mm, dd = int(monthDate[:2]), int(monthDate[3:])
return sum(daysPerMonth[:mm - 1]) + dd
count = min(monthDaytoDays(leaveAlice), monthDaytoDays(leaveBob)) - max(monthDaytoDays(arriveAlice), monthDaytoDays(arriveBob)) + 1
return count if count > 0 else 0 | count-days-spent-together | [Python] Beginner Friendly Explained | javiermora | 0 | 13 | count days spent together | 2,409 | 0.428 | Easy | 32,894 |
https://leetcode.com/problems/count-days-spent-together/discuss/2698319/Fast-Python-Solution | class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0]
arriveAliceMonth = int(arriveAlice[:2])
arriveAliceDay = int(arriveAlice[3:])
leaveAliceMonth = int(leaveAlice[:2])
leaveAliceDay = int(leaveAlice[3:])
arriveBobMonth = int(arriveBob[:2])
arriveBobDay = int(arriveBob[3:])
leaveBobMonth = int(leaveBob[:2])
leaveBobDay = int(leaveBob[3:])
alice = [0]*365
bob = [0]*365
for month in range(1, 13):
if month >= arriveAliceMonth and month <= leaveAliceMonth:
if month == arriveAliceMonth == leaveAliceMonth:
for day in range(arriveAliceDay, leaveAliceDay + 1):
alice[sum(days[:month-1]) + day - 1] = 1
elif month == arriveAliceMonth:
for day in range(arriveAliceDay, days[month-1] + 1):
alice[sum(days[:month-1]) + day - 1] = 1
elif month == leaveAliceMonth:
for day in range(1, leaveAliceDay + 1):
alice[sum(days[:month-1]) + day - 1] = 1
else:
for day in range(1, days[month-1] + 1):
alice[sum(days[:month-1]) + day - 1] = 1
if month >= arriveBobMonth and month <= leaveBobMonth:
if month == arriveBobMonth == leaveBobMonth:
for day in range(arriveBobDay, leaveBobDay + 1):
bob[sum(days[:month-1]) + day - 1] = 1
elif month == arriveBobMonth:
for day in range(arriveBobDay, days[month-1] + 1):
bob[sum(days[:month-1]) + day - 1] = 1
elif month == leaveBobMonth:
for day in range(1, leaveBobDay + 1):
bob[sum(days[:month-1]) + day - 1] = 1
else:
for day in range(1, days[month-1] + 1):
bob[sum(days[:month-1]) + day - 1] = 1
return sum(list(a&b for a,b in zip(alice,bob))) | count-days-spent-together | Fast Python Solution | scifigurmeet | 0 | 3 | count days spent together | 2,409 | 0.428 | Easy | 32,895 |
https://leetcode.com/problems/count-days-spent-together/discuss/2626968/Python | class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
arrive = max(arriveAlice, arriveBob)
leave = min(leaveAlice, leaveBob)
if arrive > leave:
return 0
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
ma, ml = int(arrive[:2]) - 1, int(leave[:2]) - 1
da, dl = int(arrive[3:]), int(leave[3:])
if ma != ml:
return days[ma] - da + 1 + sum(days[ma+1:ml]) + dl
else:
return dl - da + 1 | count-days-spent-together | Python | blue_sky5 | 0 | 6 | count days spent together | 2,409 | 0.428 | Easy | 32,896 |
https://leetcode.com/problems/count-days-spent-together/discuss/2594275/Python-oror-Impossible-To-Understand-oror-Just-Math-oror-Now-with-explanation | class Solution:
def countDaysTogether(self, a1: str, l1: str, a2: str, l2: str) -> int:
m1, d1, m2, d2, m3, d3, m4, d4 = map(int, "-".join((a1, l1, a2, l2)).split("-"))
return round(-d1/4 + d2/4 - d3/4 + d4/4 - 89*m1**11/39916800 + 197*m1**10/1209600 - 7619*m1**9/1451520 + 3961*m1**8/40320 - 102151*m1**7/86400 + 551161*m1**6/57600 - 76767407*m1**5/1451520 + 3000629*m1**4/15120 - 892222217*m1**3/1814400 + 19117439*m1**2/25200 - 1294781*m1/1980 + 89*m2**11/39916800 - 197*m2**10/1209600 + 7619*m2**9/1451520 - 3961*m2**8/40320 + 102151*m2**7/86400 - 551161*m2**6/57600 + 76767407*m2**5/1451520 - 3000629*m2**4/15120 + 892222217*m2**3/1814400 - 19117439*m2**2/25200 + 1294781*m2/1980 - 89*m3**11/39916800 + 197*m3**10/1209600 - 7619*m3**9/1451520 + 3961*m3**8/40320 - 102151*m3**7/86400 + 551161*m3**6/57600 - 76767407*m3**5/1451520 + 3000629*m3**4/15120 - 892222217*m3**3/1814400 + 19117439*m3**2/25200 - 1294781*m3/1980 + 89*m4**11/39916800 - 197*m4**10/1209600 + 7619*m4**9/1451520 - 3961*m4**8/40320 + 102151*m4**7/86400 - 551161*m4**6/57600 + 76767407*m4**5/1451520 - 3000629*m4**4/15120 + 892222217*m4**3/1814400 - 19117439*m4**2/25200 + 1294781*m4/1980 - abs(19958400*d1 - 19958400*d3 + 178*m1**11 - 13002*m1**10 + 419045*m1**9 - 7842780*m1**8 + 94387524*m1**7 - 763909146*m1**6 + 4222207385*m1**5 - 15843321120*m1**4 + 39257777548*m1**3 - 60564046752*m1**2 + 52205569920*m1 - 178*m3**11 + 13002*m3**10 - 419045*m3**9 + 7842780*m3**8 - 94387524*m3**7 + 763909146*m3**6 - 4222207385*m3**5 + 15843321120*m3**4 - 39257777548*m3**3 + 60564046752*m3**2 - 52205569920*m3)/79833600 - abs(19958400*d2 - 19958400*d4 + 178*m2**11 - 13002*m2**10 + 419045*m2**9 - 7842780*m2**8 + 94387524*m2**7 - 763909146*m2**6 + 4222207385*m2**5 - 15843321120*m2**4 + 39257777548*m2**3 - 60564046752*m2**2 + 52205569920*m2 - 178*m4**11 + 13002*m4**10 - 419045*m4**9 + 7842780*m4**8 - 94387524*m4**7 + 763909146*m4**6 - 4222207385*m4**5 + 15843321120*m4**4 - 39257777548*m4**3 + 60564046752*m4**2 - 52205569920*m4)/79833600 + abs(19958400*d1 - 19958400*d2 + 19958400*d3 - 19958400*d4 + 178*m1**11 - 13002*m1**10 + 419045*m1**9 - 7842780*m1**8 + 94387524*m1**7 - 763909146*m1**6 + 4222207385*m1**5 - 15843321120*m1**4 + 39257777548*m1**3 - 60564046752*m1**2 + 52205569920*m1 - 178*m2**11 + 13002*m2**10 - 419045*m2**9 + 7842780*m2**8 - 94387524*m2**7 + 763909146*m2**6 - 4222207385*m2**5 + 15843321120*m2**4 - 39257777548*m2**3 + 60564046752*m2**2 - 52205569920*m2 + 178*m3**11 - 13002*m3**10 + 419045*m3**9 - 7842780*m3**8 + 94387524*m3**7 - 763909146*m3**6 + 4222207385*m3**5 - 15843321120*m3**4 + 39257777548*m3**3 - 60564046752*m3**2 + 52205569920*m3 - 178*m4**11 + 13002*m4**10 - 419045*m4**9 + 7842780*m4**8 - 94387524*m4**7 + 763909146*m4**6 - 4222207385*m4**5 + 15843321120*m4**4 - 39257777548*m4**3 + 60564046752*m4**2 - 52205569920*m4 + abs(19958400*d1 - 19958400*d3 + 178*m1**11 - 13002*m1**10 + 419045*m1**9 - 7842780*m1**8 + 94387524*m1**7 - 763909146*m1**6 + 4222207385*m1**5 - 15843321120*m1**4 + 39257777548*m1**3 - 60564046752*m1**2 + 52205569920*m1 - 178*m3**11 + 13002*m3**10 - 419045*m3**9 + 7842780*m3**8 - 94387524*m3**7 + 763909146*m3**6 - 4222207385*m3**5 + 15843321120*m3**4 - 39257777548*m3**3 + 60564046752*m3**2 - 52205569920*m3) + abs(19958400*d2 - 19958400*d4 + 178*m2**11 - 13002*m2**10 + 419045*m2**9 - 7842780*m2**8 + 94387524*m2**7 - 763909146*m2**6 + 4222207385*m2**5 - 15843321120*m2**4 + 39257777548*m2**3 - 60564046752*m2**2 + 52205569920*m2 - 178*m4**11 + 13002*m4**10 - 419045*m4**9 + 7842780*m4**8 - 94387524*m4**7 + 763909146*m4**6 - 4222207385*m4**5 + 15843321120*m4**4 - 39257777548*m4**3 + 60564046752*m4**2 - 52205569920*m4) - 39916800)/79833600 + 1/2) | count-days-spent-together | Python || Impossible To Understand || Just Math || Now with explanation | NotTheSwimmer | 0 | 11 | count days spent together | 2,409 | 0.428 | Easy | 32,897 |
https://leetcode.com/problems/count-days-spent-together/discuss/2590765/Python3-easy-solution-cast-to-date-index | class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
def cast_to_index(time):
month, date = [int(x) for x in time.split('-')]
lookup = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
start = 0
for i in range(12):
start += lookup[i]
lookup[i] = start
if month == 1:
return date
else:
return lookup[month-2] + date
return max(0, min(cast_to_index(leaveAlice), cast_to_index(leaveBob)) - max(cast_to_index(arriveAlice), cast_to_index(arriveBob)) + 1) | count-days-spent-together | Python3 easy solution cast to date index | xxHRxx | 0 | 12 | count days spent together | 2,409 | 0.428 | Easy | 32,898 |
https://leetcode.com/problems/count-days-spent-together/discuss/2588550/Python3-Parse-strings | class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def fn(date):
m, d = map(int, date.split('-'))
return sum(days[:m-1]) + d
arrive = max(fn(arriveAlice), fn(arriveBob))
leave = min(fn(leaveAlice), fn(leaveBob))
return max(0, leave-arrive+1) | count-days-spent-together | [Python3] Parse strings | ye15 | 0 | 11 | count days spent together | 2,409 | 0.428 | Easy | 32,899 |
Subsets and Splits