diff --git a/03. Data Structures/Queues/LEARN b/03. Data Structures/Queues/LEARN new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/03. Data Structures/Queues/LEARN @@ -0,0 +1 @@ + diff --git a/07. Functional Programming/enumerate.py b/07. Functional Programming/enumerate.py new file mode 100644 index 0000000..eef1904 --- /dev/null +++ b/07. Functional Programming/enumerate.py @@ -0,0 +1,4 @@ +fruits = ['apple', 'banana', 'cherry', 'grape'] + +for index, fruit in enumerate(fruits, 1): + print(index, fruit) diff --git a/14. Questions/leetcode 1011 - capacity to ship packages.py b/14. Questions/leetcode 1011 - capacity to ship packages.py new file mode 100644 index 0000000..ad5e4da --- /dev/null +++ b/14. Questions/leetcode 1011 - capacity to ship packages.py @@ -0,0 +1,33 @@ +# capacity to ship packages within D days | leetcode 1011 | https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/ +# binary search on a range of min and max capacity required +# min capacity = max(weights) and max capacity = sum(weights) + +class Solution: + def shipWithinDays(self, weights: list[int], days: int) -> int: + low, high = max(weights), sum(weights) + res = high + + # check if days required for a capacity is less than D + def isPossible (capacity): + daysReq = 1 + window = capacity + for weight in weights: + if window - weight < 0: + window = capacity + daysReq += 1 + window -= weight + + return daysReq <= days + + # binary search on [min...max] + while low <= high: + mid = (high + low) // 2 + + if isPossible(mid): + res = min(res, mid) + high = mid - 1 + else: + low = mid + 1 + + return res + diff --git a/14. Questions/leetcode 103 - zigzag level order traversal.py b/14. Questions/leetcode 103 - zigzag level order traversal.py new file mode 100644 index 0000000..59d42a8 --- /dev/null +++ b/14. Questions/leetcode 103 - zigzag level order traversal.py @@ -0,0 +1,37 @@ +# binary tree zigzag level order traversal | leetcode 103 | https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal +# use flag to keep track of reversed levels; O(n) because worst case is full level - n/2 elements + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def zigzagLevelOrder(self, root: TreeNode) -> list[list[int]]: + res = [] + tempQ = [] + zig = False + + # queue to track visits + tempQ.append(root) + LtempQ = len(tempQ) + + # keep iterating till: + # the track queue is empty + while LtempQ is not 0: + LtempQ = len(tempQ) + level = [] + for i in range(LtempQ): + node = tempQ.pop(0) # pop this node from queue (visited) + if node is not None: + level.append(node.val) # add this node to the level + tempQ.append(node.left) # add left child to queue (to visit) + tempQ.append(node.right) # add right child to queue (to visit) + + if len(level) is not 0: # add level and reverse if zig + res.append(reversed(level) if zig else level) + zig = not zig + + return res \ No newline at end of file diff --git a/14. Questions/leetcode 28 - index of first occurrence.py b/14. Questions/leetcode 28 - index of first occurrence.py new file mode 100644 index 0000000..e059e17 --- /dev/null +++ b/14. Questions/leetcode 28 - index of first occurrence.py @@ -0,0 +1,26 @@ +# find the index of the first occurrence of a string | leetcode 28 | https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/ +# sliding window to match each character of the haystack with the needle; no slices. + +class Solution: + def strStr(self, haystack: str, needle: str) -> int: + # ----- using regex ----- + # if needle == '': + # return 0 + + # import re + # match = re.search(needle, haystack) + # return match.start() if match else -1 + + # ----- using sliding windows ----- + ptrL, ptrR = 0, 0 + N_needle, N_haystack = len(needle), len(haystack) + while ptrR < N_haystack: + if haystack[ptrR] == needle[ptrR - ptrL]: + ptrR += 1 + if ptrR - ptrL > N_needle - 1: + return ptrL + else: + ptrR = ptrL + 1 + ptrL += 1 + + return -1 diff --git a/14. Questions/leetcode 427 - construct quad tree.py b/14. Questions/leetcode 427 - construct quad tree.py new file mode 100644 index 0000000..f2dba66 --- /dev/null +++ b/14. Questions/leetcode 427 - construct quad tree.py @@ -0,0 +1,37 @@ +# construct quad tree | leetcode 427 | https://leetcode.com/problems/construct-quad-tree/ +# recursively call each quad of the grid and check if each quad is uniform or not + +# Definition for a QuadTree node. +class Node: + def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): + self.val = val + self.isLeaf = isLeaf + self.topLeft = topLeft + self.topRight = topRight + self.bottomLeft = bottomLeft + self.bottomRight = bottomRight + + +class Solution: + def construct(self, grid: list[list[int]]) -> Node: + def checkThisQuad(row, col, n) -> bool: + for i in range(row, row + n): + for j in range(col, col + n): + if grid[i][j] != grid[row][col]: + return False + return True + + def quadTree(row, col, n): + if checkThisQuad(row, col, n): + return Node(grid[row][col], 1, None, None, None, None) + + + return Node(grid[row][col], 0, + quadTree(row, col, n//2), + quadTree(row, col + n//2, n//2), + quadTree(row + n//2, col, n//2), + quadTree(row + n//2, col + n//2, n//2) + ) + + return quadTree(0, 0, len(grid)) + diff --git a/14. Questions/leetcode 443 - string compression.py b/14. Questions/leetcode 443 - string compression.py new file mode 100644 index 0000000..098546c --- /dev/null +++ b/14. Questions/leetcode 443 - string compression.py @@ -0,0 +1,22 @@ +# string compression | leetcode 443 | https://leetcode.com/problems/string-compression/ +# sliding window to keep track of a char's occurence + +class Solution: + def compress(self, chars: list[str]) -> int: + ptrL, ptrR = 0, 0 + total = 0 + chars += " " + + while ptrR < len(chars): + if chars[ptrL] != chars[ptrR]: + chars[total] = chars[ptrL] + total += 1 + group = ptrR - ptrL + if group > 1: + for x in str(group): + chars[total] = x + total += 1 + ptrL = ptrR + ptrR += 1 + + return total diff --git a/14. Questions/leetcode 494 - target sum.py b/14. Questions/leetcode 494 - target sum.py new file mode 100644 index 0000000..ddc9e1b --- /dev/null +++ b/14. Questions/leetcode 494 - target sum.py @@ -0,0 +1,22 @@ +# target sum | leetcode 494 | https://leetcode.com/problems/target-sum/ +# 0/1 knapsack to decide +/- and cache (index, total) + +class Solution: + def findTargetSumWays(self, nums: list[int], target: int) -> int: + N = len(nums) + mem = dict() + + if N == 0: + return 0 + + def knapsack(n, s): + if n == N: + return 1 if s == target else 0 + + if (n, s) in mem: + return mem[(n, s)] + + mem[(n, s)] = knapsack(n+1, s + nums[n]) + knapsack(n+1, s - nums[n]) + return mem[(n, s)] + + return knapsack(0, 0) diff --git a/14. Questions/leetcode 502 - ipo.py b/14. Questions/leetcode 502 - ipo.py new file mode 100644 index 0000000..e48b6e1 --- /dev/null +++ b/14. Questions/leetcode 502 - ipo.py @@ -0,0 +1,21 @@ +# IPO | leetcode 502 | https://leetcode.com/problems/ipo/ +# min-heap to track capital and max-heap to track profits + +import heapq + +class Solution: + def findMaximizedCapital(self, k: int, w: int, profits: list[int], capital: list[int]) -> int: + maxHeap = [] + minHeap = [(c, p) for c, p in zip(capital, profits)] + heapq.heapify(minHeap) + + for _ in range(k): + while minHeap and minHeap[0][0] <= w: + _, p = heapq.heappop(minHeap) + heapq.heappush(maxHeap, -1 * p) + if not maxHeap: + break + w += -1 * heapq.heappop(maxHeap) + + return w + diff --git a/14. Questions/leetcode 540 - single element in a sorted array.py b/14. Questions/leetcode 540 - single element in a sorted array.py new file mode 100644 index 0000000..fe28feb --- /dev/null +++ b/14. Questions/leetcode 540 - single element in a sorted array.py @@ -0,0 +1,24 @@ +# single element in a sorted array | leetcode 540 | https://leetcode.com/problems/single-element-in-a-sorted-array/ +# binary search over sorted array; check if mid is even and mid is the first of the duplicates + +class Solution: + def singleNonDuplicate(self, nums: list[int]) -> int: + N = len(nums) + if N < 2: + return nums[0] + low, high, mid = 0, N, 0 + while low <= high: + mid = low + ((high - low) // 2) + + if mid == N - 1: + return nums[mid] + + if nums[mid] == nums[mid - 1] or nums[mid] == nums[mid + 1]: + if (mid % 2 == 0) == (nums[mid] == nums[mid + 1]): + low = mid + else: + high = mid + else: + return nums[mid] + + return nums[mid] \ No newline at end of file diff --git a/14. Questions/leetcode 783 - minimum distance between bst nodes.py b/14. Questions/leetcode 783 - minimum distance between bst nodes.py new file mode 100644 index 0000000..9129953 --- /dev/null +++ b/14. Questions/leetcode 783 - minimum distance between bst nodes.py @@ -0,0 +1,33 @@ +# minimum distance between bst nodes | leetcode 783 | https://leetcode.com/problems/minimum-distance-between-bst-nodes +# dfs; inorder; keep track of last traversed node and check against minimum difference + + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def minDiffInBST(self, root: TreeNode) -> int: + stack = [] + curr = root + last = None + minDiff = float("inf") + while True: + if curr is not None: + stack.append(curr) + curr = curr.left + elif stack: + curr = stack.pop() + if last is not None: + minDiff = min(abs(last.val - curr.val), minDiff) + last = curr + curr = curr.right + else: + break + + return int(minDiff) + diff --git a/14. Questions/leetcode 989 - add to array form of integer.py b/14. Questions/leetcode 989 - add to array form of integer.py new file mode 100644 index 0000000..6fbd9ef --- /dev/null +++ b/14. Questions/leetcode 989 - add to array form of integer.py @@ -0,0 +1,19 @@ +# add to array form of integer | leetcode 989 | https://leetcode.com/problems/add-to-array-form-of-integer + +class Solution: + def addToArrayForm(self, num: list[int], k: int) -> list[int]: + n = len(num) - 1 + carry = 0 + while k or carry: + k, digit = k // 10, k % 10 + each = carry + digit + if n < 0: + num.insert(0, each % 10) + else: + each = each + num[n] + num[n] = each % 10 + carry = each // 10 + n -= 1 + + return num + diff --git a/loggerMiddleware.js b/loggerMiddleware.js new file mode 100644 index 0000000..25925e8 --- /dev/null +++ b/loggerMiddleware.js @@ -0,0 +1,29 @@ +const express = require('express'); +const app = express(); + +// Middleware function to log requests +app.use((req, res, next) => { + console.log(`Received a ${req.method} request to ${req.url}`); + next(); // Call next() to move to the next middleware or route handler +}); + +// Middleware function to check if the request contains a specific header +app.use((req, res, next) => { + if (req.headers.authorization) { + console.log('Authorization header present'); + } else { + console.log('Authorization header not present'); + } + next(); +}); + +// Route handler +app.get('/', (req, res) => { + res.send('Hello, World!'); +}); + +// Starting the server +const PORT = process.env.PORT || 3000; +app.listen(PORT, () => { + console.log(`Server is running on port ${PORT}`); +}); diff --git a/server.js b/server.js new file mode 100644 index 0000000..ec24f31 --- /dev/null +++ b/server.js @@ -0,0 +1,32 @@ +// Import required modules +const express = require('express'); + +// Create an Express application +const app = express(); + +// Middleware function to log requests +app.use((req, res, next) => { + console.log(`Received a ${req.method} request to ${req.url}`); + next(); // Call next() to move to the next middleware or route handler +}); + +// Middleware function to check if the request contains a specific header +app.use((req, res, next) => { + if (req.headers.authorization) { + console.log('Authorization header present'); + } else { + console.log('Authorization header not present'); + } + next(); +}); + +// Route handler +app.get('/', (req, res) => { + res.send('Hello, World!'); +}); + +// Starting the server +const PORT = process.env.PORT || 3000; +app.listen(PORT, () => { + console.log(`Server is running on port ${PORT}`); +});