Skip to content

Commit

Permalink
Get Ancestors
Browse files Browse the repository at this point in the history
  • Loading branch information
BravesDevs committed Jun 30, 2024
1 parent a9814b2 commit ec65ff1
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
34 changes: 34 additions & 0 deletions lc_daily/py/getAncestors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from collections import defaultdict


class Solution:
def getAncestors(self, n, edges):
graph = defaultdict(list)
res = {i: [] for i in range(n)}

for edge in edges:
graph[edge[0]].append(edge[1])

def dfs(parent, child):
res[child].extend(res[parent])
if parent not in res[child]:
res[child].append(parent)
res[child] = sorted(set(res[child]))
if child in graph:
parent = child
for child in graph[parent]:
dfs(parent, child)
else:
return


for edge in edges:
dfs(edge[0], edge[1])

res = dict(sorted(res.items()))
return list(res.values())


sln = Solution()
print(sln.getAncestors(
9, [[7, 5], [2, 5], [0, 7], [0, 1], [6, 1], [2, 4], [3, 5]]))
34 changes: 34 additions & 0 deletions lc_daily/py/longestSubarray1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from collections import deque


class Solution:
def longestSubarray(self, nums, limit):
min_q = deque()
max_q = deque()

l = 0
res = 0

for r in range(len(nums)):
while min_q and nums[r] < min_q[-1]:
min_q.pop()
while max_q and nums[r] > max_q[-1]:
max_q.pop()

min_q.append(nums[r])
max_q.append(nums[r])

while min_q and max_q and (max_q[0]-min_q[0]) > limit:
if nums[l] == max_q[0]:
max_q.popleft()
if nums[l] == min_q[0]:
min_q.popleft()
l += 1
res = max(res, r-l+1)

return res


sln = Solution()
result = sln.longestSubarray([8, 2, 4, 7], 4)
print(result)

0 comments on commit ec65ff1

Please sign in to comment.